
import {uuid} from '@/utils';
import loader from '@/ui/loader';
import message from '@/ui/message';

class RuntimeManager {
    constructor() {
        this.page=null
        this.pageId='';
        this.uiInstance={}
    }

    firstRender(opts) {
        const {pagePath,bridgeId}=opts
        const options=this.makeVueOptions({path:pagePath,bridgeId});
        const root=document.querySelector('#root');
        this.pageId=bridgeId;
        this.page=new Vue(options).$mount();
        //挂载到页面中
        root.appendChild(this.page.$el);
        root.addEventListener('scroll',function(){
            message.send({
                type:'pageScroll',
                body:{
                    scrollTop:root.scrollTop,
                    id:bridgeId,
                }
            })
        },false);
    }
    makeVueOptions(opts){
        const {path,bridgeId}=opts
        const staticModules=loader.getModuleByPath(path);
        const self=this;
        const { scopeId } = staticModules.moduleInfo;
        return {
            _scopeId:scopeId,
            data(){
                return {
                    ...staticModules.data
                }
            },
            created(){
                console.log("ui:created")
                self.uiInstance[self.pageId]=this;
                //向原生层发送消息
                message.send({
                    type:'moduleCreated',
                    body:{
                        id:self.pageId,
                        path
                    }
                })
            },
            beforeCreate(){
                this._bridgeInfo={
                    id:self.pageId,
                }
            },
            mounted(){
                //向原生层发送消息
                message.send({
                    type:'moduleMounted',
                    body:{
                        id:self.pageId,
                    }
                })
            },
            render:staticModules.moduleInfo.render,
        }
    }
    updateModule(opts){
        const {id,data}=opts
        const viewModule=this.uiInstance[id];
        for(let key in data){
            Vue.set(viewModule,key,data[key]);
        }
    }

}

export default new RuntimeManager();